#ifndef BOOTLOADER_H
#define BOOTLOADER_H

#include <QObject>
#include <QSerialPort>
#include <QFile>

class Bootloader : public QObject
{
    Q_OBJECT

public:
    explicit Bootloader(QObject *parent = nullptr);
    ~Bootloader();

    bool connectSerial(const QString &portName, int baudRate);
    void disconnectSerial();
    bool isConnected() const;

    void programDevice(const QString &filePath);
    void eraseDevice();
    void resetDevice();

signals:
    void progressUpdated(int progress, const QString &message);
    void operationFinished(bool success, const QString &message);
    void errorOccurred(const QString &error);
    void logMessage(const QString &message);

private slots:
    void handleReadyRead();
    void handleError(QSerialPort::SerialPortError error);

private:
    bool sendCommand(const QByteArray &command);
    bool waitForAck(int timeout = 3000);
    bool sendData(const QByteArray &data);
    QByteArray readData(int timeout = 3000);

    void processBootloaderResponse(const QByteArray &response);

private:
    QSerialPort *m_serial;
    bool m_connected;
    QByteArray m_receiveBuffer;
};

#endif // BOOTLOADER_H
